//
//  DBManager.m
//  DBManger
//
//  Created by qianfeng on 16/1/24.
//  Copyright (c) 2016年 qianfeng. All rights reserved.
//

#import "DBManager.h"
#import "FMDB.h"
#define db_path [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/sqllite.db"]

@implementation DBManager
{
    FMDatabase * _dataBase;
}
#pragma mark - 单例对象
+(DBManager *)manager{
    
    static DBManager * manager = nil;
    @synchronized(self) {
        if (!manager) {
        manager = [[DBManager alloc] init];
        }
    }
    return manager;
}

-(id)init{
    if (self = [super init]) {
        
    }
    return self;
}
#pragma mark - 创建普通表
-(void)createNormalTable:(NSString *)tableName{

        _dataBase = [[FMDatabase alloc] initWithPath:db_path];
        if ([_dataBase open]) {
        
            NSString * sql = [@"create table if not exists " stringByAppendingFormat:@"%@(data blob)",tableName];
            if ([_dataBase executeUpdate:sql]){
                NSLog(@"创建成功!");
            }else{
                NSLog(@"创建失败!");
            }
        }
}

#pragma mark - 创建详细数据表
-(void)createTable:(NSString *)tableName andSql:(NSString *)sql{
    
    _dataBase = [[FMDatabase alloc] initWithPath:db_path];
    if ([_dataBase open]) {
        
        NSString * sqls = [NSString stringWithFormat:@"create table if not exists %@(%@)",tableName,sql];
        if ([_dataBase executeUpdate:sqls]){
            NSLog(@"创建成功!");
        }else{
            NSLog(@"创建失败!");
        }
    }
}

#pragma mark - 查询数据
-(FMResultSet *)selectDataWithSql:(NSString *)sql{
    
    NSString * selectSql = [NSString stringWithFormat:@"select * from %@",sql];
    if ([_dataBase open]) {
        FMResultSet * rs = [_dataBase executeQuery:selectSql];
        return rs;
    }
    return nil;
}

#pragma mark - 插入数据
-(void)insertDataWithSql:(NSString *)sql{
    
    NSString * insertSql = [NSString stringWithFormat:@"insert into %@",sql];

    [self doUpdate:insertSql];
}

#pragma mark - 删除数据
-(void)deleteDataWithSql:(NSString *)sql{
    
    NSString * deleteSql = [NSString stringWithFormat:@"delete from %@",sql];
    
    [self doUpdate:deleteSql];
}

#pragma mark - 修改数据
-(void)updateDataWithSql:(NSString *)sql{
    
    NSString * updateSql = [NSString stringWithFormat:@"update %@",sql];
    
    [self doUpdate:updateSql];
}

-(void)doUpdate:(NSString *)sql{
    
    if ([_dataBase open]) {
        if ([_dataBase executeUpdate:sql]) {
            NSLog(@"操作成功!");
        }else{
            NSLog(@"操作失败!");
        }
    }
}

@end
